<?php

class Bus_BusController extends App_Controller_Action
{
    /**
     * @var Bus_Model_Bus
     */
    private $_model;

    public function init()
    {
        $this->_model = new Bus_Model_Bus();
    }

    public function listAction()
    {
        $rows = $this->_model->fetchAll($this->_model->select()->order('bus_name'));
        $this->_helper->json->sendJson(array('data' => $rows->toArray()));
    }

    public function saveAction()
    {
        $form = new Bus_Form_Bus();
        $params = $this->_getAllParams();
        if (!$form->isValid($params)) {
            $errors = $form->getErrorMessages();
            $this->sendErrors($errors);
            return;
        }
        $values = $form->getValues();
        $routes = Zend_Json::decode($values['bus_routes']);
        unset($values['bus_routes']);
        unset($values['bus_pid']);
        if ($params['bus_pid']) {
            $row = $this->_model->find($params['bus_pid'])->current();
            $row->setFromArray($values);
            $row->save();
        } else {
            $row = $this->_model->createRow($values);
            $row->save();
        }
        $row->setRoutes($routes);
        $this->sendSuccess();
    }

    public function loadAction()
    {
        $id = $this->_getParam('id', 0);
        if (!$id) {
            $this->sendErrors('Incorrect id');
        }
        $row = $this->_model->find($id)->current();
        $data = $row->toArray();
        $data['routes'] = $row->getRoutes();
        $this->_helper->json->sendJson($data);
    }

    public function removeAction()
    {
        $id = $this->_getParam('id');
        $where = $this->_model->getAdapter()->quoteInto('bus_pid = ?', $id);
        $this->_model->delete($where);
        $this->sendSuccess();
    }
}